<template>
	<div class="layout-padding">
		<div class="layout-padding-auto layout-padding-view">
			<el-row shadow="hover" v-show="showSearch" class="ml10">
				<el-form :inline="true" :model="state.queryForm" @keyup.enter="getDataList" ref="queryRef">
					<el-form-item label="楼层名" prop="floorName">
						<el-input placeholder="请输入楼层名" clearable style="max-width: 180px" v-model="state.queryForm.floorName" />
					</el-form-item>
          <el-form-item label="楼宇" prop="buildingId">
            <el-select v-model="state.queryForm.buildingId" placeholder="请选择楼宇" clearable @change="getUnit">
              <el-option v-for="building in buildingList" :key="building.buildingId" :label="building.buildingName" :value="building.buildingId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单元" prop="unitId">
            <el-select v-model="state.queryForm.unitId" placeholder="请先选择楼宇" clearable>
              <el-option v-for="unit in unitList" :key="unit.unitId" :label="unit.unitName" :value="unit.unitId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="query" class="ml10" icon="search" type="primary">
              查询
            </el-button>
            <el-button @click="onOpenAddMenu" class="ml10" icon="plus" type="primary">
              新增
            </el-button>
            <el-button @click="resetQuery" icon="Refresh">
              重置
            </el-button>
            <el-button @click="handleDelete(selectObjs, selectFloors)" icon="Refresh" :disabled="multiple">
              删除
            </el-button>
          </el-form-item>
				</el-form>
			</el-row>
      <el-table
          :data="state.dataList"        style="width: 100%"
          v-loading="state.loading"
          @selection-change="handleSelectionChange"
          border
          :cell-style="tableStyle.cellStyle"
          :header-cell-style="tableStyle.headerCellStyle"
      >
        <!-- 根据实际字段调整表格列 -->
        <el-table-column type="selection" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="序号" type="index" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="楼层" prop="floorNumber" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="楼层名称" prop="floorName" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="楼宇名称" prop="buildingName" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="单元名称" prop="unitName" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="房间数" prop="rooms" show-overflow-tooltip width="auto">
          <template #default="scope">
            <el-link
                v-if="scope.row.rooms > 0"
                type="primary"
                @click="goToRoomIndex(scope.row.floorId)"
            >
              {{ scope.row.rooms }}
            </el-link>
            <span v-else>{{ scope.row.rooms }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="创建人" prop="createBy" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip width="auto"></el-table-column>
        <el-table-column label="操作" width="auto">
          <template #default="scope">
            <el-button icon="edit-pen" @click="onOpenEditRoom(scope.row)" text type="primary">
              编辑
            </el-button>
            <el-button icon="delete" @click="handleDelete([scope.row.floorId], [scope.row.floorNumber])" text type="primary">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-bind="state.pagination" @current-change="currentChangeHandle" @size-change="sizeChangeHandle"> </pagination>
		</div>
		<MenuDialog @refresh="getDataList()" ref="menuDialogRef" />
    <ResidentDialog @refresh1="getDataList()" ref="menuDialogRef1" />
	</div>
</template>

<script lang="ts" name="systemMenu" setup>
import { BasicTableProps, useTable } from '/@/hooks/table';
import { useMessage, useMessageBox } from '/@/hooks/message';
import { roomList, deleteRoom, getBuildingList, getUnitList } from '/@/api/room/room';
import { floorList, deleteFloor } from "/@/api/floor/floor";
import { onMounted } from "vue";
import router from "/@/router";
// 引入组件
const MenuDialog = defineAsyncComponent(() => import('./form.vue'));
const ResidentDialog = defineAsyncComponent(() => import('./residentForm.vue'));

// 定义变量内容
const tableRef = ref();
const menuDialogRef = ref();
const menuDialogRef1 = ref();
const queryRef = ref();
const showSearch = ref(true);
const state: BasicTableProps = reactive<BasicTableProps>({
	pageList: floorList, // H
	queryForm: {
    floorName: '',
    buildingId: undefined,
    unitId: undefined
	},
	isPage: true,
});
const buildingList = ref([]);
const unitList = ref([]);

// 多选rows
const selectObjs = ref([]) as any;
const selectFloors = ref([]) as any;
// 是否可以多选
const multiple = ref(true);
//单选判断
const single = computed(() => selectObjs.value.length !== 1);

const { getDataList, tableStyle, currentChangeHandle, sizeChangeHandle } = useTable(state);

onMounted(() => {
  getBuilding();
});

// 打开新增菜单弹窗
const onOpenAddMenu = (row?: any) => {
	menuDialogRef.value.openDialog("新增楼层", row);
};
// 打开编辑菜单弹窗
const onOpenEditRoom = (row: any) => {
	menuDialogRef.value.openDialog("修改楼层", row);
};

//跳转房间页面
const goToRoomIndex = (floorId: number) => {
  router.push({
    path: '/room/index',
    query: {
      floorId: floorId
    }
  })
}

// 多选事件
const handleSelectionChange = (objs: { floorId: string, floorNumber: string }[]) => {
  selectObjs.value = objs.map(({ floorId }) => floorId);
  selectFloors.value = objs.map(({ floorNumber }) => floorNumber);
  multiple.value = !objs.length;
};



const toggleExpand = (children: any[], unfold = true) => {
	for (const key in children) {
		tableRef.value?.toggleRowExpansion(children[key], unfold);
		if (children[key].children) {
			toggleExpand(children[key].children!, unfold);
		}
	}
};

// 搜索事件
const query = () => {
  state.dataList = [];
  getDataList();
};
// 加载楼宇
const getBuilding = async () => {
  const res = await getBuildingList();
  buildingList.value = res.data.data;
};

// 根据楼宇加载单元
const getUnit = async (buildingId: Number) => {
  const res = await getUnitList(buildingId);
  unitList.value = res.data.data;
};

// 清空搜索条件
const resetQuery = () => {
  queryRef.value.resetFields();
  state.dataList = [];
  unitList.value = [];
  getDataList();
};

// 删除操作
const handleDelete = async (ids: Number[], floorNumbers: string[]) => {
	try {
		await useMessageBox().confirm('您确定要删除' + floorNumbers + '楼层吗');
	} catch {
		return;
	}

	try {
		await deleteFloor(ids);
		getDataList();
		useMessage().success('删除成功');
	} catch (err: any) {
		useMessage().error(err.msg);
	}
};
</script>
